import axios from "axios";
// import { MessageBox, Message } from "element-ui";
import { message } from 'ant-design-vue';
import store from "@/store";
import { getToken } from "@/utils/auth";
import Router from '../router'
import { useStore } from 'vuex';
// create an axios instance
const service = axios.create({
  //  baseURL:'/api',// process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests

  timeout: 1000000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    store.dispatch("user/setloadding",'yes')
    if (store.getters.token) {
   
      config.headers["Authorization"] = sessionStorage.getItem('token');
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
 
  response => {
    setTimeout(() => {
      store.dispatch("user/setloadding",'no')
    }, 100);
  
    const res = response.data;
    if (!res.success) {
      if (res.size) {
        return res;
      }
      if(!response.request.responseURL.includes('judgeRemove')) {
     
        message.error(res.message || res.data || "Error",5);
      }
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.message === "401" || res.code === 50012 || res.code === 50014) {
        // store.dispatch("tagsView/delAllVisitedViews");
        // store.dispatch("tagsView/delAllCachedViews");
        // message.error(res.message || res.data || "Error",5);
      }
      return Promise.reject(new Error(res.message || res.data || "Error"));
    } else {
      return res;
    }
  },
  error => {
    console.log("err", error.response); // for debug
    let res = error.response;
    if (res.status == 401) {
      store.dispatch("tagsView/delAllVisitedViews");
      store.dispatch("tagsView/delAllCachedViews");
      store.dispatch('user/logout').then(() => {
        Router.push({
          path: '/login'
        })
      })
    }else{
      message.error(
        error.message,
        5,
      );
    }
    return Promise.reject(error);
  }
);

export default service;
